﻿Option Explicit On
Option Strict On

Imports System
Imports System.Security.Permissions
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Security
Imports Microsoft.SharePoint.Utilities
Imports Microsoft.SharePoint.Workflow

Public Class FolderToDocSetUpdateItemReceiver
    Inherits SPItemEventReceiver

    ''' <summary>
    ''' An item is updating.  Linked to Document Libraries.
    ''' </summary>
    Public Overrides Sub ItemUpdated(properties As SPItemEventProperties)
        MyBase.ItemUpdated(properties)


        Dim progid As String = properties.ListItem.ProgId
        Dim NewContentTypeId As SPContentTypeId
        Dim NewContentType As SPContentType

        Try
            NewContentTypeId = New SPContentTypeId(properties.AfterProperties("ContentTypeId").ToString)
            NewContentType = properties.List.ContentTypes(NewContentTypeId)
        Catch ex As Exception
            Throw New Exception("FolderToDocSetUpdateItemReceiver could not determine current ContentType.", ex)
        End Try

        If String.IsNullOrEmpty(progid) AndAlso IsDocSet(NewContentType) Then
            'Fix the document set (Change icon from folder to doc set and enable doc set page and functionality)
            Try
                EventFiringEnabled = False
                properties.ListItem.ProgId = "SharePoint.DocumentSet"
                properties.ListItem.Update()
            Catch ex As Exception
                EventFiringEnabled = True
            End Try
        End If

    End Sub

    Private Function IsDocSet(ct As SPContentType) As Boolean

        Dim loopCount As Integer = 0
        Do Until ct.Name = "Document Set" OrElse ct.Parent Is Nothing OrElse ct.Parent.Name = "System"
            loopCount += 1
            ct = ct.Parent
            If loopCount = 50 Then
                Throw New Exception("FolderToDocSetUpdateItemReceiver exceeded maximum number of inherited content type parsing (25 layers deep).  Document set conversion fix will not be applied.")
                Return False
            End If
        Loop

        Select Case ct.Name
            Case "Document Set"
                Return True
            Case Else
                Return False
        End Select
    End Function

End Class
